<template>
  <div class="employees">

    <el-button type="primary" @click="onAddOpen">新增员工</el-button>

    <custom-table
      :current-page.sync="page.current"
      :page-size.sync="page.size"
      :table-props="{
        size: 'mini',
        border: true,
      }"
      :data="list.rows"
      :columns="columns"
      :total="list.total"
      @update:currentPage="onPageChange"
      @update:pageSize="onPageSizeChange"
    >
      <template v-slot="{ row, col, data }">
        <el-avatar
          v-if="col.prop === 'staffPhoto'"
          :src="data"
        />
        <span v-if="col.prop === 'formOfEmployment'">
          {{ formOfEmploymentMapping[data] }}
        </span>
        <el-switch
          v-if="col.prop === 'status'"
          disabled
        />
        <template v-if="col.prop === 'op'">
          <el-button type="text" size="mini">查看</el-button>
          <el-button type="text" size="mini">转正</el-button>
          <el-button type="text" size="mini">调岗</el-button>
          <el-button type="text" size="mini">离职</el-button>
          <el-button type="text" size="mini" @click="onRoleOpen(row.id)">角色</el-button>
          <el-button type="text" size="mini" @click="onEmployeeRemove(row.id)">删除</el-button>
        </template>
			</template>
    </custom-table>

    <!-- 新增弹窗 -->
    <el-dialog
      :title="$t('employees.dialogTip.add.title')"
      :visible.sync="addVisible"
      @close="closeAddDialog"
      destroy-on-close
    >
      <el-form
        :model="addParams"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item
          label="姓名"
          prop="username"
        >
          <el-input v-model="addParams.username" placeholder="请输入姓名" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="addParams.mobile" placeholder="请输入手机号" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="入职时间"
          prop="timeOfEntry"
        >
          <el-date-picker
            v-model="addParams.timeOfEntry"
            type="date"
            placeholder="请选择入职时间"
          />
        </el-form-item>
        <el-form-item
          label="聘用形式"
          prop="formOfEmployment"
        >
          <el-select v-model="addParams.formOfEmployment" placeholder="请选择聘用形式">
            <el-option label="正式" :value="1" />
            <el-option label="非正式" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="工号"
          prop="workNumber"
        >
          <el-input v-model="addParams.workNumber" placeholder="请输入工号" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门"
          prop="departmentName"
        >
          <el-input
            ref="departmentName"
            :value="addParams.departmentName"
            placeholder="请输入部门"
            autocomplete="off"
            @focus="onDepartmentTreeExpand"
          />
          <el-tree
            v-show="departmentTreeVisible"
            :data="departmentList"
            default-expand-all
            node-key="id"
            :props="{
              children: 'children',
              label: 'name',
            }"
            @node-click="onDepartmentTreeNodeClick"
          />
        </el-form-item>
        <el-form-item
          label="转正时间"
          prop="correctionTime"
        >
          <el-date-picker
            v-model="addParams.correctionTime"
            type="date"
            placeholder="请选择转正时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddDialog">取 消</el-button>
        <el-button type="primary" @click="onAddOk">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色弹窗 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleVisible"
      @close="closeRoleDialog"
      destroy-on-close
    >
      <el-checkbox-group v-model="checkedRoleList">
        <el-checkbox
          v-for="role in roleList.rows"
          :label="role.id"
          :key="role.id"
        >
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeRoleDialog">取 消</el-button>
        <el-button type="primary" @click="onRoleOk">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import * as api from '@/api/employees';

// 判断是否为空
function getCheckEmptyFunc (field) {
  return function (rule, value, callback) {
    if (!value) {
      callback(new Error(this.$t('employees.dialogTip.add.' + field)));
    } else {
      callback();
    }
  }
}

function checkMobile (rule, value, callback) {
  if (!(/^[1][3,5,7,8][0-9]\d{8}$/.test(value))) {
    callback(new Error(this.$t('employees.dialogTip.add.mobile')));
  } else {
    callback();
  }
}

function checkDepartmentName (rule, value, callback) {
  if (value === '请选择部门名称') {
    callback(new Error(this.$t('employees.dialogTip.add.departmentName')));
  } else {
    callback();
  }
}

let currentId = '';

export default {
  data () {
    return {
      // 分配角色选中的元素
      // store: checkedRoleIdList
      checkedRoleList: [],
      // 是否显示角色弹窗
      roleVisible: false,
      // 新增弹窗内是否显示部门列表
      departmentTreeVisible: false,
      // 是否显示新增弹窗
      addVisible: false,
      // 新增表单的参数
      addParams: {
        formOfEmployment: 1,
        departmentName: '请选择部门名称',
      },
      addRules: {
        username: [{ required: true, trigger: 'blur', validator: getCheckEmptyFunc('username').bind(this) }],
        mobile: [{ required: true, trigger: 'blur', validator: checkMobile.bind(this) }],
        timeOfEntry: [{ required: true, trigger: 'blur', validator: getCheckEmptyFunc('timeOfEntry').bind(this) }],
        formOfEmployment: [{ required: true, trigger: 'change', validator: getCheckEmptyFunc('formOfEmployment').bind(this) }],
        workNumber: [{ required: true, trigger: 'blur', validator: getCheckEmptyFunc('workNumber').bind(this) }],
        departmentName: [{ required: true, trigger: 'blur', validator: checkDepartmentName.bind(this) }],
      },
      // 聘用形式映射关系
      // 0: 外包; 1: 正式; 2: 外聘;
      formOfEmploymentMapping: {
        0: '外包',
        1: '正式',
        2: '外聘',
      },
      columns: [
        {
          label: '序号',
          // 没有prop的时候 显示索引
          width: 60,
        },
        {
          label: '姓名',
          prop: 'username',
          sortable: true,
        },
        {
          label: '头像',
          prop: 'staffPhoto',
          needSlot: true,
        },
        {
          label: '手机号',
          prop: 'mobile',
          sortable: true,
        },
        {
          label: '工号',
          prop: 'workNumber',
          sortable: true,
        },
        {
          label: '聘用形式',
          prop: 'formOfEmployment',
          needSlot: true,
          sortable: true,
        },
        {
          label: '部门',
          prop: 'departmentName',
          sortable: true,
        },
        {
          label: '入职时间',
          prop: 'timeOfEntry',
          sortable: true,
        },
        {
          label: '状态',
          prop: 'status', // to fix
          needSlot: true,
        },
        {
          label: '操作',
          prop: 'op',
          needSlot: true,
          fixed: 'right',
          width: 250,
        },
      ],
      page: {
        current: 1,
        size: 5,
      },
    };
  },
  computed: {
    ...mapState('employees', [
      'list',
      'departmentList',
    ]),
    ...mapState('role', {
      roleList: state => state.list,
    }),
  },
  methods: {
    ...mapActions('employees', [
      'updateList',
      'updateDepartmentList',
    ]),
    ...mapActions('role', {
      updateRoleList: 'updateList',
    }),
    // 删除员工
    onEmployeeRemove (id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(async () => {
        const res = await api.remove(id);
        this.$message({
          message: res.message,
          type: res.success ? 'success' : 'error',
        });
        if (res.success) {
          // 刷新列表
          this.updateList({
            page: this.page.current,
            size: this.page.size,
          });
        }
      })
      .catch(() => {});
    },
    // 关闭角色弹窗
    closeRoleDialog () {
      this.roleVisible = false;
      // 置空数据
      this.checkedRoleList = [];
    },
    // 打开角色弹窗
    async onRoleOpen (id) {
      this.roleVisible = true;
      // 在外面把id记住
      currentId = id;
      // 发请求
      const list = await api.getCheckedRoleIdList(id);
      // 设置反显
      this.checkedRoleList = list;
    },
    // 分配角色确认
    async onRoleOk () {
      const res = await api.setEmployeeRoles({
        id: currentId,
        roleIds: this.checkedRoleList,
      });
      this.$message({
        message: res.message,
        type: res.success ? 'success' : 'error',
      });
      if (res.success) {
        // 关弹窗
        this.closeRoleDialog();
      }
    },
    // 点击部门列表元素
    onDepartmentTreeNodeClick (node) {
      // 手动设置焦点
      this.$refs.departmentName.focus();
      // input赋值
      this.addParams.departmentName = node.name;
      // 收起部门列表
      this.departmentTreeVisible = false;
      // 手动失去焦点
      this.$refs.departmentName.blur();
    },
    // 展开部门列表
    onDepartmentTreeExpand () {
      this.departmentTreeVisible = true;
    },
    // 关闭新增弹窗
    closeAddDialog () {
      this.addVisible = false;
      // 表单置空
      this.addParams = {
        formOfEmployment: 1,
        departmentName: '请选择部门名称',
      };
    },
    onAddOpen () {
      this.addVisible = true;
    },
    // 新增确定
    async onAddOk () {
      const res = await api.add(this.addParams);
      this.$message({
        message: res.message,
        type: res.success ? 'success' : 'error',
      });
      if (res.success) {
        // 关弹窗
        this.closeAddDialog();
        // 刷新列表
        this.updateList({
          page: this.page.current,
          size: this.page.size,
        });
      }
    },
    // 页数改变时
    onPageChange (current) {
      this.updateList({
        page: current,
        size: this.page.size,
      });
    },
    // 页码改变时
    onPageSizeChange (size) {
      this.page.current = 1;
      this.updateList({
        page: 1,
        size: size,
      });
    },
  },
  created () {
    this.updateList({
      page: this.page.current,
      size: this.page.size,
    });
    // 初始化部门列表
    this.updateDepartmentList();
    // 初始化角色列表
    this.updateRoleList();
  },
}
</script>

<style lang="less" scoped>

</style>